package com.lzk.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzk.common.CustomerException;
import com.lzk.common.R;
import com.lzk.pojo.Category;
import com.lzk.pojo.Dish;
import com.lzk.pojo.Setmeal;
import com.lzk.service.CategoryService;
import com.lzk.service.DishService;
import com.lzk.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Resource
    private CategoryService categoryService;
    @Resource
    private DishService dishService;
    @Resource
    private SetmealService setmealService;
    @PostMapping
    public R<String> save(@RequestBody Category category){
        log.info(category.toString());
        categoryService.save(category);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page<Category>> pageR(int page,int pageSize){
        Page<Category> categoryPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        categoryService.page(categoryPage,lqw);
        return R.success(categoryPage);
    }
    @PutMapping
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success("修改成功");
    }
    @DeleteMapping()
    public R<String> delete(Long id) throws CustomerException {
        log.info(id.toString());
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Dish::getCategoryId,id);
        int count1 = dishService.count(lqw);
        if (count1>0){
            throw new CustomerException("该菜品分类有关联到其他菜品，删除失败");
        }
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Setmeal::getCategoryId,id);
        int count2 = setmealService.count(queryWrapper);
        if (count2>0){
            throw new CustomerException("该菜品分类有关联到其他套餐，删除失败");
        }

        categoryService.removeById(id);
        return R.success("删除成功");
    }
    //展示下拉列表
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        log.info(category.toString());
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        Integer type = category.getType();
        lqw.eq(type!=null,Category::getType,type);
        List<Category> categoryList = categoryService.list(lqw);
        return R.success(categoryList);
    }
}
